﻿//using GYCTOAManagementSystemNewApi.Model;
//using GYCTOAManagementSystemNewApi.Model.Enum;
//using GYCTOAManagementSystemNewApi.Model.Tool;
//using GYCTOAManagementSystemNewApi.Model.ViewModel;
//using GYCTOAManagementSystemNewApi.Public;
//using Microsoft.AspNetCore.Authorization;
//using Microsoft.AspNetCore.Http;
//using Microsoft.AspNetCore.Mvc;
//using Microsoft.EntityFrameworkCore;
//using Microsoft.Extensions.Logging;
//using Newtonsoft.Json;
//using Newtonsoft.Json.Linq;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Threading.Tasks;

//namespace GYCTOAManagementSystemNewApi.Controllers
//{
//    [Route("api/[controller]")]
//    [ApiController]
//    [Authorize]
//    public class DepartmentController : Controller
//    {


//        private readonly ILogger<CustomerController> _logger;
//        DBContext _db;
//        PublicTool _publictool;
//        public DepartmentController(ILogger<CustomerController> logger, DBContext db)
//        {
//            _logger = logger;
//            _db = db;
//            _publictool = new PublicTool(_db);
//        }

//        #region 组织架构(部门)
//        /// <summary>
//        /// 显示初始化数据
//        /// </summary>
//        /// <param name="formData"></param>
//        /// <returns></returns>
//        [HttpPost("GetDepartment")]
//        public JsonResult GetDepartment([FromBody] dynamic formData)
//        {
//            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
//            var limit = Convert.ToInt32(jsondata["limit"].ToString());
//            var offset = Convert.ToInt32(jsondata["offset"].ToString());
//            string like = (jsondata["like"].ToString());
//            //int limit, int offset)
//            var uselis = _db.Users.ToList();
//            var list = JsonConvert.DeserializeObject<List<DepartmentNew>>(JsonConvert.SerializeObject(_db.Department.Where(x => !x.Delete && !x.IsRevoke).ToList()));
//            foreach (var item in list)
//            {
//                var newlis = uselis.Where(x => x.DepartmentId == item.Id && !x.InternshipState.Equals((int)InternshipStateEnum.Quit)).ToList();
//                item.PeopleCount = newlis.Count();
//                foreach (var nelis in newlis)
//                {
//                    item.AllWages += nelis.SalaryStandard;
//                }
//                var parklis = uselis.Where(x => x.DepartmentId == item.Id && x.UserPosition == "15").ToList();
//                if (parklis.Count > 0)
//                {
//                    item.PartOwnerTwo = parklis.FirstOrDefault().Id;
//                }
//            }
//            list = list.Where(x => x.DepartmentName.Contains(like) || x.DepartmentNumber.Contains(like)).OrderBy(x=>x.Index).ToList();
//            var total = list.Count;
//            var rows = list.Skip((offset - 1) * limit).Take(limit).ToList();
//            return new JsonResult(new { code = 0, msg = "", count = total, data = rows });
//        }
//        /// <summary>
//        /// 添加功能
//        /// </summary>
//        /// <param name="formData"></param>
//        /// <returns></returns>
//        [HttpPost("AddDepartment")]
//        public JsonResult AddDepartment([FromBody] dynamic formData)
//        {
//            //punchclock punchclock)
//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
//            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
//            var department = JsonConvert.DeserializeObject<DepartmentNew>(jsondata["AddDepartment"].ToString());
//            PublicTool.GetOpDataOpId(department, author);
//            var PartOwnerUser = _db.Users.Where(x=>x.Id.Equals(department.PartOwnerTwo)).FirstOrDefault();
//            if (PartOwnerUser!=null)
//            {
//                PartOwnerUser.UserPosition = "15";
//            }
//            var indexDepar = _db.Department.Where(x => !x.Delete && !x.IsRevoke).OrderByDescending(x => x.Index).FirstOrDefault();
//            department.Index = indexDepar.Index + 1;
//            _db.Department.Add(department);
//            var flag = _db.SaveChanges() > 0;
//            return new JsonResult(new { bit = flag });
//        }

//        /// <summary>
//        /// 修改组织架构
//        /// </summary>
//        /// <param name="formData"></param>
//        /// <returns></returns>
//        [HttpPost("UpdateDepartment")]
//        public JsonResult UpdateDepartment([FromBody] dynamic formData)
//        {
//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
//            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
//            var department = JsonConvert.DeserializeObject<DepartmentNew>(jsondata["UpDepartment"].ToString());
//            if (department.PartOwnerTwo != 0)
//            {
//                var userlis = _db.Users.Where(x => x.DepartmentId.Equals(department.Id) && x.UserPosition.Equals("15")).ToList();
//                foreach (var ite in userlis)
//                {
//                    ite.UserPosition = "";
//                }               
//                var PartOwnerUser = _db.Users.Where(x => x.Id.Equals(department.PartOwnerTwo)).FirstOrDefault();
//                if (PartOwnerUser != null)
//                {
//                    PartOwnerUser.UserPosition = "15";
//                }
//            }
//            else 
//            {
//                var user = _db.Users.Where(x => x.DepartmentId.Equals(department.Id) && x.UserPosition.Equals("15")).FirstOrDefault();
//                if (!user.Id.Equals(department.PartOwnerTwo))
//                {
//                    user.UserPosition = "";
//                    _db.Users.Where(x => x.Id.Equals(department.PartOwnerTwo)).FirstOrDefault().UserPosition = "15";
//                }
//            }
//            //(Department department)
//            PublicTool.GetOpDataOpId(department, author);
//            var entry = _db.Entry<Department>(department);
//            entry.State = EntityState.Unchanged;
//            entry.Property(t => t.DepartmentNumber).IsModified = true; //设置要更新的属性
//            entry.Property(t => t.DepartmentName).IsModified = true; //设置要更新的属性
//            entry.Property(t => t.PartOwner).IsModified = true;
//            entry.Property(t => t.LeaderShip).IsModified = true;
//            entry.Property(t => t.SectoralFunctions).IsModified = true;
//            entry.Property(t => t.SuperiorDepartmentsId).IsModified = true;
//            entry.Property(t => t.Code).IsModified = true;
//            entry.Property(t => t.YearOutputValue).IsModified = true;
//            entry.Property(t => t.DepartType).IsModified = true;
//            entry.Property(t => t.Remarks).IsModified = true;
//            entry.Property(t => t.OperatDate).IsModified = true;
//            entry.Property(t => t.OperatId).IsModified = true;
//            var flag = _db.SaveChanges() > 0;
//            return new JsonResult(new { bit = flag });
//        }

//        /// <summary>
//        /// 部门撤销
//        /// </summary>
//        /// <param name="formData"></param>
//        /// <returns></returns>
//        [HttpPost("RevokeDepartment")]
//        public JsonResult RevokeDepartment([FromBody] dynamic formData)
//        {
//            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
//            var DepartmentId = Convert.ToInt32(jsondata["DepartmentId"].ToString());
//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
//            var flag = false;
//            var obj = _db.Department.Find(DepartmentId);
//            if (obj == null)
//            {
//                return new JsonResult(new { bit = false });
//            }
//            obj.IsRevoke = true;
//            PublicTool.GetOpDataOpId(obj, author);
//            flag = _db.SaveChanges() > 0;
//            return new JsonResult(new { bit = flag });
//        }

//        /// <summary>
//        /// 部门删除
//        /// </summary>
//        /// <param name="formData"></param>
//        /// <returns></returns>
//        [HttpPost("DelDepartment")]
//        public JsonResult DelDepartment([FromBody] dynamic formData)
//        {
//            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
//            var id = Convert.ToInt32(jsondata["Id"].ToString());
//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
//            var flag = false;
//            var obj = _db.Department.Find(id);
//            if (obj == null)
//            {
//                return new JsonResult(new { bit = false });
//            }
//            obj.Delete = true;
//            PublicTool.GetOpDataOpId(obj, author);
//            flag = _db.SaveChanges() > 0;
//            return new JsonResult(new { bit = flag });
//        }
//        /// <summary>
//        /// 调整部门顺序
//        /// </summary>
//        /// <param name="formData"></param>
//        /// <returns></returns>
//        [HttpPost("UpdateDepartmentIndex")]
//        public JsonResult UpdateDepartmentIndex([FromBody] dynamic formData)
//        {
//            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
//            var index = Convert.ToInt32(jsondata["Index"].ToString());
//            var departmentId = Convert.ToInt32(jsondata["DepartmentId"].ToString());
//            var depart = _db.Department.Where(x => x.Id == departmentId).FirstOrDefault();
//            var newIndex = depart.Index;
//            Department dep;
//            if (index == 1)
//            {
//                dep = _db.Department.Where(x => !x.Delete && !x.IsRevoke && x.Index < newIndex).OrderByDescending(x=>x.Index).FirstOrDefault();
//            }
//            else {
//                dep = _db.Department.Where(x => !x.Delete && !x.IsRevoke && x.Index > newIndex).OrderBy(x=>x.Index).FirstOrDefault();
//            }
//            if (dep != null)
//            {
//                depart.Index = dep.Index;
//                dep.Index = newIndex;
//            }
//            var flag = _db.SaveChanges() > 0;
//            return new JsonResult(new { bit = flag });
//        }
//        #endregion

//        #region 职位管理
//        //   [Authorize(Roles = "Admin,010200")]
//        [HttpPost("PosiTionMain")]
//        public JsonResult PosiTionMain([FromBody] dynamic formData)
//        {
//            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
//            var name =  (jsondata["name"].ToString());
//            //查询所有职位
//            var data = _db.DutyMains.Where(x => !x.Delete).OrderBy(x => x.Id).OrderBy(x => x.Level).ToList();
//            if (!string.IsNullOrWhiteSpace(name))
//            {
//                data = data.Where(x => x.DutyName.Contains(name)).ToList();
//            }
//            return new JsonResult(new { data = data });
//        }

//        /// <summary>
//        /// 添加职位
//        /// </summary>
//        /// <returns></returns>
//      //  [Authorize(Roles = "Admin,010200")]
//        [HttpPost("AddPosiTion")] 
//        public JsonResult AddPosiTion([FromBody] dynamic formData)
//        {
//            Message message = new Message();
//            try
//            {
//                var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
//                var DutyMain = JsonConvert.DeserializeObject<DutyMains>(jsondata["AddPosiTionMain"].ToString());
//                var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//                PublicTool.GetOpDataOpId(DutyMain, author);
//                var result = _db.DutyMains.Where(x => x.DutyName.Equals(DutyMain.DutyName)).FirstOrDefault();
//                if (result != null)
//                {
//                    message.IsSuccess = false;
//                    message.Msg = "此职务已存在,不可重复添加!";
//                    return new JsonResult(new { message });
//                }
//                else 
//                {
//                    _db.DutyMains.Add(DutyMain);
//                    message.IsSuccess = _db.SaveChanges() > 0 ;
//                    message.Msg = message.IsSuccess ? "添加成功":"添加失败,请重试!";
//                    return new JsonResult(new { message });
//                }            
//            }
//            catch (Exception)
//            {
//                message.IsSuccess = false;
//                message.Msg = "服务器异常!";
//                return new JsonResult(new { message });
//            }
//        }

//        /// <summary>
//        /// 删除职务
//        /// </summary>
//        /// <param name="dutyMain"></param>
//        /// <returns></returns>
//        //[Authorize(Roles = "Admin,010200")]
//        [HttpPost("DletePosiTion")]

//        public JsonResult DletePosiTion([FromBody] dynamic formData)
//        {
//            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
//            var id = Convert.ToInt32(jsondata["id"].ToString());
//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            var query = from dutyMain in _db.DutyMains
//                        where dutyMain.Id == id
//                        select dutyMain;
//            DutyMains duty = query.FirstOrDefault();
//            if (duty != null)
//            {
//                //db.DutyMains.Remove(duty);
//                duty.Delete = true;
//                PublicTool.GetOpDataOpId(duty, author);
//            }
//            return new JsonResult(new { bit = _db.SaveChanges() > 0 });
//        }
//        /// <summary>
//        /// 更新职务
//        /// </summary>
//        /// <returns></returns>
//        [HttpPost("UpdateDuty")]
//        public JsonResult UpdateDuty([FromBody] dynamic formData)
//        {
//            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
//            var duty = JsonConvert.DeserializeObject<DutyMains>(jsondata["UpPosiTionMain"].ToString());
//            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
//            PublicTool.GetOpDataOpId(duty, author);
//            var entry = _db.Entry<DutyMains>(duty);
//            entry.State = EntityState.Unchanged;
//            entry.Property(t => t.Remarks).IsModified = true;
//            entry.Property(t => t.DutyName).IsModified = true; //设置要更新的属性
//            entry.Property(t => t.Level).IsModified = true; //设置要更新的属性
//            var flag = _db.SaveChanges() > 0;
//            return new JsonResult(new { bit = flag });
//        }
//        #endregion

//        #region 部门人员管理
//        /// <summary>
//        /// 修改人员所属组织架构
//        /// </summary>
//        /// <param name="formData"></param>
//        /// <returns></returns>
//        [HttpPost("UpdateUserDepartment")]
//        public JsonResult UpdateUserDepartment([FromBody] dynamic formData)
//        {
//            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
//            var userId = JsonConvert.DeserializeObject<List<int>>(jsondata["userId"].ToString());
//            var departmentId = Convert.ToInt32(jsondata["DepartmentId"].ToString());
//            foreach (var u in userId)
//            {
//                var user = _db.Users.Where(x => x.Id == u).FirstOrDefault();
//                user.DepartmentId = departmentId;
//            }
//            var flag = _db.SaveChanges() > 0;
//            return new JsonResult(new { bit = flag });
//        }
//        /// <summary>
//        /// 删除人员所属组织架构
//        /// </summary>
//        /// <param name="formData"></param>
//        /// <returns></returns>
//        [HttpPost("DelUserDepartment")]
//        public JsonResult DelUserDepartment([FromBody] dynamic formData)
//        {
//            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
//            var userId = JsonConvert.DeserializeObject<List<int>>(jsondata["userId"].ToString());
//            foreach (var u in userId)
//            {
//                var user = _db.Users.Where(x => x.Id == u).FirstOrDefault();
//                user.DepartmentId = 0;
//            }
//            var flag = _db.SaveChanges() > 0;
//            return new JsonResult(new { bit = flag });
//        }
//        #endregion
//    }
//}
